

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


/**
 * @author oven:
 * @version 创建时间：2013-1-31 下午5:20:58
 * 
 */
public class HmacSHA1Encryption {
	private static final String MAC_NAME="HmacSHA1";
	private static final String ENCODING = "UTF-8";
	
	
	public static String HmacSHAEncrypt(String encryptText,String encryptKey){
		try{
			byte[] data = encryptKey.getBytes(ENCODING);
			//根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
			SecretKey secretKey = new SecretKeySpec(data,MAC_NAME);
			//生成一个指定算法的MAC对象
			Mac mac = Mac.getInstance(MAC_NAME);
			//用给定密钥初始化Mac对象
			mac.init(secretKey);
			byte[] text = encryptText.getBytes(ENCODING);
			//完成mac操作
			byte[] digest = mac.doFinal(text);
			StringBuilder sBuilder = bytesToHexString(digest);
			return sBuilder.toString();
		}catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 转换成hex
	 * @param bytesArray
	 * @return
	 */
	public static StringBuilder bytesToHexString(byte[] bytesArray){
		if(bytesArray==null){
			return null;
		}
		StringBuilder sbBuilder = new StringBuilder();
		for(byte b:bytesArray){
			String hv = String.format("%02x",b);
			sbBuilder.append(hv);
		}
		return sbBuilder;
	}

}

